//
//  DAUEnginResultsTVC.m
//  DAU-iOS
//
//  Created by XiangDongMBP on 2016/11/17.
//  Copyright © 2016年 East. All rights reserved.
//

#import "DAUEnginResultsTVC.h"
#import "NSString+XDIsEmpty.h"
#import <MJRefresh.h>
#import "DAUMonDetailVC.h"

@interface DAUEnginResultsTVC ()

@property (nonatomic, readonly) DAUEngineRoomModel *model;

@end

static NSInteger const kPageSize = 15;  //!< 每次请求的记录数

@implementation DAUEnginResultsTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (DAUEngineRoomModel *)model {
    return DAU_APP_DELEGATE.dauModel.engineSeaResult;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initSubViews {
    //下拉、上拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
    self.tableView.mj_footer.automaticallyHidden = YES;
}

- (void)refreshNewData {
//    [self.tableView.mj_header beginRefreshing];
    [self tableViewRefresh:self.tableView.mj_header];
}

#pragma mark - <UITableViewDataSource>代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.result.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = (UITableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
    
    if (indexPath.row < self.model.result.count) {
        [self configureCell:cell forProduct:self.model.result[indexPath.row]];
    }
    
    return cell;
}

#pragma mark - 网络请求
- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    NSInteger startIndex = isHeader ? 0 : self.model.result.count;
    NSString *urlStr = [DAUUrlProtocolMerger apiCollectorList];
    NSDictionary *pars = @{@"page"   : @(startIndex),
                           @"size"   : @(kPageSize),
                           @"keyword": self.keywords};
    
    [XDAFHttpRequest GET:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求机房列表返回 %@", responseObject);
        if ([responseObject[@"errCode"] integerValue] == 200) {
            DAUEngineRoomModel *temp = [DAUEngineRoomModel yy_modelWithJSON:responseObject];
            if (isHeader || !DAU_APP_DELEGATE.dauModel.engineSeaResult) {
                DAU_APP_DELEGATE.dauModel.engineSeaResult = temp;
            } else {
                [DAU_APP_DELEGATE.dauModel.engineSeaResult addMoreWithData:temp];
            }
            [self tableViewEndRefresh:isHeader withMoreData:temp.result.count];
            [self.tableView reloadData];
        } else {
            [self tableViewEndRefresh:isHeader withMoreData:YES];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"result"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求机房列表失败 %@", error);
        [self tableViewEndRefresh:isHeader withMoreData:YES];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:NSLocalizedString(@"网络请求失败", nil)];
    }];
}

- (void)tableViewEndRefresh:(BOOL)isHeader withMoreData:(BOOL)more {
    if (isHeader) {
        [self.tableView.mj_footer resetNoMoreData];
        [self.tableView.mj_header endRefreshing];
    } else {
        if (more) {
            [self.tableView.mj_footer resetNoMoreData];
            [self.tableView.mj_footer endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }
}

@end
